package com.warmlight.voicepacket.ui.user.usercenter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.preview.ImagePreviewActivity;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.MyPlaylistAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.ui.communitylm.widget.ReportDialog;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.ui.user.fragment.OtherCommunityFragment;
import com.warmlight.voicepacket.ui.user.fragment.OtherCoverFragment;
import com.warmlight.voicepacket.ui.user.fragment.OtherSoundFragment;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

public class LookUserCenterActivity extends BaseActivity implements View.OnClickListener {

    private ImageButton ib_setting;
    private CircularImageView ci_header;
    private TextView tv_nickname;
    private TextView tv_id;
    private TextView tv_age;
    private TextView tv_gander;
    private TextView tv_sign;
    //    private ImageView iv_add_cover;
//    private ListView lv_my_playlist;
//    private MyCoverListOnNetAdapter adapter;
//    private LinearLayout ll_login;
//    private LinearLayout ll_nologin;
    private MyPlaylistAdapter mMyPlaylistAdapter;
    private List<DBFloatPlaylist> mPlaylist;
    private ImageView iv_edit;
    private RelativeLayout rl_msg;
    private TextView tv_msg_num;
    private IUnReadMessageObserver iUnReadMessageObserver;
    private int integer_msg_num;
    private int chat_msg_num;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private UserCenterViewpagerAdapter userCenterViewpagerAdapter;
    private String uid;
    private CircularImageView iv_header;
    private TextView tv_header_nickname;
    private ImageView iv_more;
    private String type;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_usercenter);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            uid = bundle.getString("uid");
            MobclickAgent.onEvent(getContext(),MobClickHelper.GSTATE,uid);
            type = bundle.getString("type");// cover    sound     video
            initView();
            initViewPager();
            loadData();
        }
    }

    private void initView() {
        setBack();
        ib_setting = (ImageButton) findViewById(R.id.ib_setting);
        ci_header = (CircularImageView) findViewById(R.id.ci_header);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_id = (TextView) findViewById(R.id.tv_id);
        tv_age = (TextView) findViewById(R.id.tv_age);
        tv_gander = (TextView) findViewById(R.id.tv_gander);
        tv_sign = (TextView) findViewById(R.id.tv_sign);
//        iv_add_cover = (ImageView) findViewById(R.id.iv_add_cover);
//        lv_my_playlist = (ListView) findViewById(R.id.lv_my_playlist);
//        ll_login = (LinearLayout) findViewById(R.id.ll_login);
//        ll_nologin = (LinearLayout) findViewById(R.id.ll_nologin);
        iv_edit = (ImageView) findViewById(R.id.iv_edit);
        iv_edit.setVisibility(View.GONE);
        //我的消息
        rl_msg = (RelativeLayout) findViewById(R.id.rl_msg);
        ImageView iv_msg = (ImageView) findViewById(R.id.iv_msg);
        tv_msg_num = (TextView) findViewById(R.id.tv_msg_num);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        TextView tv_chat = findViewById(R.id.tv_chat);
        tv_chat.setOnClickListener(this);

        if (TextUtils.equals(uid,SPUtils.getLoginUid())){
            tv_chat.setVisibility(View.GONE);
        }

        iv_header = findViewById(R.id.iv_header);
        tv_header_nickname = findViewById(R.id.tv_header_nickname);
        iv_header.setVisibility(View.GONE);
        tv_header_nickname.setVisibility(View.GONE);
//        CoordinatorLayout main_content = findViewById(R.id.main_content);
//        main_content.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//
//            }
//        });
        AppBarLayout appbar = findViewById(R.id.appbar);
        final int dd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,45,getResources().getDisplayMetrics());
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int height = appBarLayout.getHeight(); //
                height = height - dd;
                verticalOffset = -verticalOffset;//0  -100

                if((height - verticalOffset)<=0){
                    iv_header.setVisibility(View.VISIBLE);
                    tv_header_nickname.setVisibility(View.VISIBLE);
                    iv_more.setVisibility(View.GONE);
                }else{
                    iv_header.setVisibility(View.GONE);
                    tv_header_nickname.setVisibility(View.GONE);
                    iv_more.setVisibility(View.VISIBLE);
                }

            }
        });

        iv_more = findViewById(R.id.iv_more);
        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReportDialog dialog = new ReportDialog();
                dialog.setID("0",uid);

                dialog.show(getSupportFragmentManager(),"report");
            }
        });
    }

    private void initViewPager() {
        TabLayout.Tab tab1 = tabLayout.newTab();
        tab1.setText("收藏");
        tabLayout.addTab(tab1);

        TabLayout.Tab tab2 = tabLayout.newTab();
        tab2.setText("声音");
        tabLayout.addTab(tab2);

        TabLayout.Tab tab3 = tabLayout.newTab();
        tab3.setText("动态");
        tabLayout.addTab(tab3);

        Bundle bundle = new Bundle();
        bundle.putString("uid",uid);

        OtherCoverFragment myCoverFragment = new OtherCoverFragment();
        myCoverFragment.setArguments(bundle);
        OtherSoundFragment myCoverFragment2 = new OtherSoundFragment();
        myCoverFragment2.setArguments(bundle);
        OtherCommunityFragment myCoverFragment3 = new OtherCommunityFragment();
        myCoverFragment3.setArguments(bundle);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(myCoverFragment);
        fragments.add(myCoverFragment2);
        fragments.add(myCoverFragment3);

        userCenterViewpagerAdapter = new UserCenterViewpagerAdapter(getSupportFragmentManager(),getContext(),fragments);
        viewPager.setAdapter(userCenterViewpagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0){
                    MobclickAgent.onEvent(getContext(),MobClickHelper.GSTATE_TAB_CLOT,uid);
                }else if (position == 1){
                    MobclickAgent.onEvent(getContext(),MobClickHelper.GSTATE_TAB_VOICE,uid);
                }else if (position == 2){
                    MobclickAgent.onEvent(getContext(),MobClickHelper.GSTATE_TAB_STATUS,uid);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if (TextUtils.equals("cover",type)){

        }else if (TextUtils.equals("sound",type)){
            viewPager.setCurrentItem(1);
        }else if (TextUtils.equals("video",type)){
            viewPager.setCurrentItem(2);
        }
    }


    private void loadData(){
        String url = HttpConfig.USER_COVER;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("uid",uid);
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response) {
//                String s = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size()>0){
                    Map<String, String> map = listMapByJson.get(0);
                    if (TextUtils.equals("200",map.get("code"))){
                        String data = map.get("data");
                        final UserCenterData userCenterData = new Gson().fromJson(data, UserCenterData.class);
                        getContext().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initData(userCenterData);
                            }
                        });


//                        ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
//                        Map<String, String> dataMap = dataList.get(0);
//                        String author = dataMap.get("author");
//                        String list = dataMap.get("list");
                    }else{
//                        SPUtils.clearLogin();
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                initData();
//                            }
//                        });
                    }
                }
            }
        });
    }

    private void initTableNum(String cover_num ,String audio_num,String post_num){
        TabLayout.Tab tab1 = tabLayout.getTabAt(0);
        tab1.setText("收藏"+cover_num);

        TabLayout.Tab tab2 = tabLayout.getTabAt(1);
        tab2.setText("声音"+audio_num);

        TabLayout.Tab tab3 = tabLayout.getTabAt(2);
        tab3.setText("动态"+post_num);
    }

    private void initData(final UserCenterData userCenterData){

        UserCenterData.TabNumBean tab_num = userCenterData.getTab_num();
        String cover_num = tab_num.getCover_num();
        String audio_num = tab_num.getAudio_num();
        String post_num = tab_num.getPost_num();
        initTableNum(cover_num,audio_num,post_num);





//        boolean ltn = SPUtils.getBoolean(SPUtils.LOCAL_TO_NET);
//        if (ltn) {
//        List<UserCenterData.ListBean> list = userCenterData.getList();
//        MyCoverFragment myCoverFragment = (MyCoverFragment) userCenterViewpagerAdapter.getItem(0);
//        myCoverFragment.setData((ArrayList<UserCenterData.ListBean>) list);
//        adapter.setList(list);
//        }
        UserCenterData.AuthorBean author = userCenterData.getAuthor();
        final String avator = author.getAvator();
//        String birth = author.getBirth();
//        String is_delay = author.getIs_delay();
//        String is_popup = author.getIs_popup();
        String nickname = author.getNickname();
        String sex = author.getSex();
        String sign = author.getSign();
        String uid = author.getUid();
        String new_birth = author.getNew_birth();

        ci_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ImagePreviewActivity.class);
                Bundle bundle = new Bundle();
                List<ImageInfo> imageInfo = new ArrayList<>();
                ImageInfo imageInfo1 = new ImageInfo();
                imageInfo1.setBigImageUrl(avator);
                imageInfo.add(imageInfo1);
                bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) imageInfo);
//                bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, index);
                intent.putExtras(bundle);
                getContext().startActivity(intent);
                ((Activity) getContext()).overridePendingTransition(0, 0);
            }
        });


        tv_nickname.setText(nickname);
        tv_header_nickname.setText(nickname);
        if (TextUtils.isEmpty(new_birth) || TextUtils.equals("0",new_birth)){
            tv_age.setVisibility(View.VISIBLE);
            tv_age.setText("0岁");
        }else{
            tv_age.setVisibility(View.VISIBLE);
            Calendar calendar = Calendar.getInstance();
            int i1 = calendar.get(Calendar.YEAR);
            calendar.setTimeInMillis(Long.valueOf(new_birth)*1000);
            int i = calendar.get(Calendar.YEAR);
            int m = i1-i;
            tv_age.setText(m+"岁");
        }
        tv_id.setText("ID:"+uid);

        if (TextUtils.equals("1",sex)){
            tv_gander.setText("男");
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.boy);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_gander.setCompoundDrawables(drawable,null,null,null);
            tv_gander.setBackgroundResource(R.drawable.shape_man_bg);
            tv_age.setBackgroundResource(R.drawable.shape_man_bg);
        }else if (TextUtils.equals("2",sex)){
            tv_gander.setText("女");
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.girl);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_gander.setCompoundDrawables(drawable,null,null,null);
            tv_gander.setBackgroundResource(R.drawable.shape_woman_bg);
            tv_age.setBackgroundResource(R.drawable.shape_woman_bg);
        }else{
            tv_gander.setText("性别保密");
//            Drawable drawable = getContext().getResources().getDrawable(R.drawable.boy);
//            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_gander.setCompoundDrawables(null,null,null,null);
            tv_gander.setBackgroundResource(R.drawable.shape_ufo_bg);
            tv_age.setBackgroundResource(R.drawable.shape_ufo_bg);
        }
        if (TextUtils.isEmpty(sign)){
            tv_sign.setText("这个人还没有个性签名哦");
        }else {
            tv_sign.setText(sign);
        }
        RequestOptions options = new RequestOptions();
        options.placeholder(R.drawable.icon_login_header).error(R.drawable.icon_login_header);
        try {
            Glide.with(getContext()).asBitmap().load(avator).apply(options).into(ci_header);
            Glide.with(getContext()).asBitmap().load(avator).apply(options).into(iv_header);
        }catch (Exception e){

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_chat:
                if (SPUtils.isLogined()){
                    RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.PRIVATE, uid, tv_nickname.getText().toString());
                    MobclickAgent.onEvent(getContext(), MobClickHelper.GSTATEZ_CHAT,uid);
                }else{
                    startActivity(new Intent(getContext(), LoginRegistActivity.class));
                }
                break;

        }
    }
}
